<template>
  <Wrapper>
    <el-card
      v-loading="loading"
      element-loading-text="pdf加载中"
      shadow="never"
      header="pdf预览"
    >
      <div class="pdf-operator">
        <el-pagination
          v-if="showAllPages"
          v-model:current-page="currentPage"
          background
          layout="prev, slot, next"
          :page-size="1"
          :total="pageCount"
        >
          {{ currentPage }} / {{ pageCount }}
        </el-pagination>
        <span v-else>共{{ pageCount }}页</span>
        <el-space :size="15">
          <el-checkbox
            v-model="showAllPages"
            @change="showAllPagesChange"
          >
            显示所有页面
          </el-checkbox>
          <el-tooltip :content="`翻转${rotations[currentRotation]}度`">
            <icon
              name="RefreshLeft"
              @click="
                currentRotation === 3
                  ? (currentRotation = 0)
                  : (currentRotation += 1)
                "
            />
          </el-tooltip>
          <el-tooltip content="打印">
            <icon
              name="Printer"
              @click="handlePrint"
            />
          </el-tooltip>
        </el-space>
      </div>

      <el-scrollbar height="calc(100vh - 300px)">
        <vue-pdf-embed
          ref="pdfRef"
          class="pdf-preview-container"
          :rotation="rotations[currentRotation]"
          :page="currentPage"
          :source="source"
          @rendered="handlePdfRendered"
        />
      </el-scrollbar>
    </el-card>
  </Wrapper>
</template>

<script setup>
import VuePdfEmbed from 'vue-pdf-embed'

const pdfRef = ref(null)
const pageCount = ref(1)
const loading = ref(true)
const currentPage = ref(1)
const currentRotation = ref(0)
const showAllPages = ref(false)
const rotations = [0, 90, 180, 270]
const source =
  'https://xiaoxian521.github.io/hyperlink/pdf/Cookie%E5%92%8CSession%E5%8C%BA%E5%88%AB%E7%94%A8%E6%B3%95.pdf'

function handlePdfRendered() {
  loading.value = false
  pageCount.value = pdfRef.value.doc.numPages
}

function handlePrint() {
  pdfRef.value.print()
}

function showAllPagesChange() {
  currentPage.value = showAllPages.value ? null : 1
}
</script>

<style scoped>
.pdf-operator {
  display: flex;
  justify-content: space-between;
  margin-bottom: var(--el-card-padding);
}

.pdf-preview-container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}
</style>
